#!/usr/bin/env python
"""
rankAbundance.py

Description:-

Give one or more pickle files as input and this shall output a white space
delimited table showing calculated biodiversity information. This includes
Shannon, Simpson & JackKnife Indices, which are indices which can be
interpreted as representations of species evenness, richness, and sampling
bias, repsectively.

Some useful options included with this program:-

    -collapse-at-rank <rank>   :-
            Collapse the result tree at rank <rank>.
    -groupX [group1files] [...] [-group2 ... [...]] :-
            * used to combine and average diversity indices over
            multiple results files.


"""

from ssummo.cmd_options import Options
from ssummo.resample import Indices
from ssummo.ssummolib import combine_dicts

import sys

try:
    import cPickle as pickle
except ImportError:
    import pickle

class LocalOptions(Options):
    def __init__(self, args):
        Options.__init__(self)
        self.options = {
            '-in': [],
            '-out' : sys.stdout,
            '-collapse-at-rank' : None,
            }
        self.singleargs = ['-out', '-collapse-at-rank']
        self.multiargs = ['-in']
        self.help_text = {
            '-in' : 'Input pickle file. Required.',
            '-out': 'Output table. [Standard output]',
            '-collapse-at-rank' :
                'Desired rank at which to collapse results tree',
            }
        self.useage = '{0} [options] <results file>.pkl'.format(__file__)
        self.parse_args(args)

def main(options):
    """Wrapper function to print everything! If you want to use it, just
    initiate a copy of LocalOptions, edit it's namespace variables as necessary
    (i.e. the options), and pass to this function.

    e.g. ::

        >>> input_files = ['one.pkl', 'two.pkl']
        >>> myoptions = LocalOptions(input_files)
        >>> myoptions['-collapse-at-rank'] = 'genus'
        >>> main( myoptions )

    """
    in_files = []
    if len( options.regopts ) > 0:
        groups = [ group for group in sorted( options.regopts.keys() )]
        dictionaries = []
        for group in groups:
            results = []
            for infile in options.regopts[group]:
                with file(infile, 'rb') as handle:
                    results.append(pickle.load(handle))
            combined_dict = combine_dicts(results)
            dictionaries.append(combined_dict)
            in_files.append('GROUP{0}'.format(group))
        combined = True
    else:
        combined = False
        dictionaries = []
        for in_file in options['-in']:
            with file(in_file, 'rb') as inFile:
                dictionary = pickle.load(inFile)
            dictionaries.append(dictionary)
            in_files.append(in_file)

    calculator = Indices(options['-out'],
                         collapse_rank=options['-collapse-at-rank'])
    calculator.print_header()
    for i, in_file in enumerate(in_files):
        calculator.load(dictionaries[i], combined, name=in_file)
        calculator.calc_all()
        print(calculator)

    if len( options['-in'] ) > 0:
        pass
    return dictionaries

if __name__ == '__main__':
    args = sys.argv[1:]
    myoptions = LocalOptions( args )
    main( myoptions )
